<template>
  <div class="app-container">
    <el-form ref="orderForm" :model="order" label-width="100px">
      <el-form-item label="买方信息">
        <el-radio-group v-model="order.platform">
          <el-radio value="1">攸汇</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="卡券信息">
        <el-button type="primary" :icon="CirclePlus" circle link @click="selectCouponVisible = true" />
      </el-form-item>
      <el-form-item>
        <el-table
          border
          :cell-style="{ textAlign: 'center', fontSize: '13px' }"
          :header-cell-style="{
            textAlign: 'center',
            fontWeight: '100',
            fontSize: '13px',
            color: 'white',
            backgroundColor: '#009688'
          }"
          :data="tableOrder"
          style="width: 100%"
        >
          <el-table-column prop="couponName" label="卡券名称" />
          <el-table-column prop="couponType" label="卡券类型" />
          <el-table-column prop="couponPrice" label="卡券原价" />
          <el-table-column prop="couponDiscount" label="卡券折扣价" />
          <el-table-column prop="useTimes" label="可使用次数" />
          <el-table-column prop="expire" label="有效时长" />
          <el-table-column prop="purchaseQuantity" label="购买张数" width="150">
            <template #default="scope">
              <el-input-number
                @change="scope.row.amount = scope.row.couponPrice * scope.row.purchaseQuantity"
                size="small"
                v-model="scope.row.purchaseQuantity"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="总金额" />
          <el-table-column fixed="right" label="操作">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleDelete(scope.row)"> 移除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div style="margin-top: 20px; text-align: right">
      <span>合计金额:</span>
      <span>{{ tableOrder.reduce((pre, cur) => pre + Number(cur.amount), 0) }}元</span>
    </div>
    <div style="margin-top: 20px; text-align: center">
      <el-button type="primary" @click="handleSubmit">卖出</el-button>
      <el-button type="info" @click="router.push('/cityLevel/cityMarket/order/index')">取消</el-button>
    </div>
  </div>
  <el-dialog v-model="selectCouponVisible" title="卡券选择" width="700" destroy-on-close center>
    <el-form :model="couponsform" class="form-line">
      <el-form-item prop="couponName">
        <el-input
          size="default"
          @keydown.enter="getCouponsList"
          v-model="couponsform.couponName"
          placeholder="卡卷名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-table
      border
      :cell-style="{ textAlign: 'center', fontSize: '13px' }"
      :header-cell-style="{
        textAlign: 'center',
        fontWeight: '100',
        fontSize: '13px',
        color: 'white',
        backgroundColor: '#009688'
      }"
      :data="couponList"
      style="width: 100%"
    >
      <el-table-column prop="couponName" label="卡券名称" />
      <el-table-column prop="couponType" label="卡券类型">
        <template #default="scope">{{ scope.row.couponType == 1 ? "配送券" : "" }}</template>
      </el-table-column>
      <el-table-column prop="couponPrice" label="卡券原价" />
      <el-table-column prop="couponDiscount" label="卡券折扣价" />
      <el-table-column prop="useTimes" label="可使用次数" />
      <el-table-column prop="expire" label="有效时长" />
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleSelect(scope.row)"> 选择 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>
<script lang="tsx" setup name="orderAdd">
import { Coupon } from "@/api/interface/city/cityMarket/coupon";
import { MarketOrder } from "@/api/interface/city/cityMarket/order";
import { getCouponListAPI } from "@/api/modules/city/cityMarket/coupon/api";
import { addOrderAPI } from "@/api/modules/city/cityMarket/order/api";
import { CirclePlus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
let order = ref<MarketOrder.AddParams>({
  province: JSON.parse(localStorage.getItem("userInfo") as string).province,
  city: JSON.parse(localStorage.getItem("userInfo") as string).city
});
let tableOrder = ref<MarketOrder.BuyInfo[]>([]);
const selectCouponVisible = ref<boolean>(false);

// 卡券
let couponsform = ref<Coupon.SearchParams>({
  province: JSON.parse(localStorage.getItem("userInfo") as string).province,
  city: JSON.parse(localStorage.getItem("userInfo") as string).city,
  couponName: "",
  pageNum: 1
});
const couponList = ref<Coupon.Row[]>([]);
const getCouponsList = async () => {
  const { rows, code, msg } = await getCouponListAPI(couponsform.value);
  if (code == "200" && rows) {
    couponList.value = rows;
  } else {
    ElMessage.error(msg);
  }
};
// 选择卡券
const handleSelect = (row: Coupon.Row) => {
  console.log(row);
  tableOrder.value.push({
    couponId: row.couponId,
    couponName: row.couponName,
    couponType: row.couponType,
    couponPrice: row.couponPrice,
    couponDiscount: row.couponDiscount,
    useTimes: row.useTimes,
    expire: row.expire,
    purchaseQuantity: 1,
    amount: row.couponPrice,
    ruleDescribe: row.ruleDescribe
  });
  getCouponsList();
  couponList.value = couponList.value.filter(item => {
    tableOrder.value.forEach(item2 => {
      if (item.couponId == item2.couponId) {
        return false;
      }
    });
    return true;
  });
  selectCouponVisible.value = false;
};

// 移除卡券
const handleDelete = (row: MarketOrder.BuyInfo) => {
  tableOrder.value = tableOrder.value.filter(item => item.couponId != row.couponId);
  getCouponsList();
  couponList.value = couponList.value.filter(item => {
    tableOrder.value.forEach(item2 => {
      if (item.couponId == item2.couponId) {
        return false;
      }
    });
    return true;
  });
};

// 提交
const handleSubmit = () => {
  order.value.amount = tableOrder.value.reduce((pre, cur) => pre + Number(cur.amount), 0);
  order.value.buyInfo = tableOrder.value;
  addOrder();
};
const addOrder = async () => {
  const { code, msg } = await addOrderAPI(order.value);
  if (code == "200") {
    ElMessage.success("提交成功");
    router.push("/cityLevel/cityMarket/order/index");
  } else {
    ElMessage.error(msg);
  }
};
onMounted(() => {
  getCouponsList();
});
</script>
<style lang="scss" scoped>
.app-container {
  padding: 15px;
  font-size: 13px;
  background: white;
}
</style>
